import { useRef, useState, useEffect } from "react"
import Process from "../Process"
import './style.less'
import {string, bool, func} from 'prop-types'
import {isMobile, fullScreen, exitFullscreen} from '../util/Utils' 
import Loading from '../loading'
// import ContextMenu from "../Contextmenu"
function Video(props){
    let {src, autoPlay, title, next} = props
    const canvas = useRef(null) // 画布实例
    const video = useRef(null) // video实例
    let Video = useRef(null) // 整体容器
    let [current, setCurrent] = useState(0) // 当前进度
    let [total, setTotal] = useState(0)     // 总时长
    let [reId, setReid] = useState(null)    // 周期id
    let [innerControls,setControls] = useState(true) // control
    let [animated, setAnimate] = useState(true) // 动画效果
    let [time, setTimer] = useState(null)   // timer 
    let [timee, setTimerr] = useState(null)   // timerr 动画延迟
    let [canvasWh, setCanvas] = useState({})    // canvas的属性
    let [loading, setLoading] = useState(true)  // loading层
    let [style, setStyle] = useState({}) // 全屏样式
    let [full, setFull] = useState() // 控制全屏按钮
    useEffect(() => {
        if(canvas.current && video.current !== null){
            video.current.onloadedmetadata = ()=>{
                setCanvas({
                    height: video.current.videoHeight * window.devicePixelRatio,
                    width: video.current.videoWidth * window.devicePixelRatio
                })
                setLoading(false)
                // console.log('源文件获取成功')
                let videoElment = video.current 
                setCurrent(videoElment.currentTime)
                setTotal(videoElment.duration)
            }
            video.current.addEventListener('waiting',(e)=>{
                // 缓冲
                // console.log('缓冲',e)
                setLoading(true)
            })
            video.current.addEventListener('playing',(e)=>{
                // 缓冲完成
                // console.log('缓冲完成',e)
                setLoading(false)
            })
            video.current.addEventListener('play',()=>{
                
                switchToCanvas()
            })
            //监听window是否全屏，并进行相应的操作,支持esc键退出
            window.onresize = function() {
                let isFull=!!(document.webkitIsFullScreen || document.mozFullScreen || 
                    document.msFullscreenElement || document.fullscreenElement
                );
                if(isFull){
                    setStyle({
                        position:'absolute',
                        left:0,
                        top:0,
                        width:window.screen.width,
                        height:window.screen.height
                    })
                }else{
                    setStyle({})
                }
                setFull(isFull)
            }
            window.addEventListener('keydown',(e)=>{
                e.preventDefault()
                // console.log(e)
                if(e.keyCode === 32){
                    playPause()
                }
            })
            // 控制自动消失
            
            // console.log('leave')
            let timer = setTimeout(()=>{
                setAnimate(false)
                let timerr = setTimeout(()=>{
                    setControls(false)
                },300)
                setTimerr(timerr)
            },3000)
            setTimer(timer)
        }
        return () => {
            cancelAnimationFrame(reId)
            clearTimeout(time)
            clearTimeout(timee)
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
    useEffect(() => {
        if(autoPlay || video.current)
            video.current.play()
    },[total, video, autoPlay])
    useEffect(()=>{
        if(video.current){
            switchToCanvas()
            video.current.play()
        }
        return ()=>{
            cancelAnimationFrame(reId)
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    },[src])
    function switchToCanvas() {
        if(video.current === null || video.current.ended){
            return;  
        }
        let videoElment = video.current 
        
        // 将video上的图片的每一帧以图片的形式绘制的canvas上
        // console.log(ctx.drawImage)
        if(!isMobile()){
            let ctx = canvas.current.getContext('2d')
            ctx.drawImage(videoElment, 0, 0, canvas.current.width, canvas.current.height);
        }
        setCurrent(videoElment.currentTime)
        setTotal(videoElment.duration)
        // throttle(()=>{
        let id = window.requestAnimationFrame(switchToCanvas);
        setReid(id)
        // },10)()
    }
    // 监听鼠标活动，显示控制栏
    function showControl(){
        clearTimeout(time)
        clearTimeout(timee)
        setAnimate(true)
        setControls(true)
        let timer = setTimeout(()=>{
            setAnimate(false)
            let timerr = setTimeout(()=>{
                setControls(false)
            },300)
            setTimerr(timerr)
        },3000)
        setTimer(timer)
    }
    // 播放暂停
    function playPause(e){
        if(video.current && innerControls){
            console.log(e?.button)
            if(e?.button === 0){
                if(!video.current.paused)
                    video.current.pause()
                else
                    video.current.play()
            }
        }
    }
    function _playPause(){
        if(video.current){
            if(!video.current.paused)
                video.current.pause()
            else
                video.current.play()
        }
    }
    function _fullScreen(){
        fullScreen(Video.current)
        if(isMobile()){
            setStyle({
                position:'absolute',
                left:0,
                top:0,
                width:window.screen.width,
                height:window.screen.height
            })
        }
    }
    function _exitFullscreen(){
        exitFullscreen()
        if(isMobile()){
            setStyle({})
        }
    }
    function _rePlay(){
        if(video.current){
            video.current.currentTime = 0
            setCurrent(video.current.currentTime)
            cancelAnimationFrame(reId)
            switchToCanvas()
            video.current.play()
        }
    }
    function _muted(){
        // console.log('静音')
        // e.stopPropagation()
        if(video.current?.muted){
            video.current.muted = false
        }else{
            video.current.muted = true
        }
    }
    function _fullOrExit(){
        let isFull=!!(document.webkitIsFullScreen || document.mozFullScreen || 
            document.msFullscreenElement || document.fullscreenElement
        );
        if(isFull){
            _exitFullscreen()
        }else{
            _fullScreen()
        }
    }
    return (
        <div 
            className="Video" 
            ref={Video}
            style={{
                height:isNaN(Video.current?.clientWidth * 0.575) ? 0 : Video.current?.clientWidth * 0.575,
                ...style,
            }}
            onMouseEnter={()=>{
                // console.log('enter')
                clearTimeout(time)
                clearTimeout(timee)
                setAnimate(true)
                setControls(true)
            }}
            onMouseMove={showControl}
            onClick={showControl}
            onMouseLeave={()=>{
                setAnimate(false)
                // console.log('leave')
                let timer = setTimeout(()=>{
                    setControls(false)
                },500)
                setTimer(timer)
            }}
        >
            {innerControls && <div className={`video-header animated faster ${animated?'fadeIn':'fadeOut'}` }>
                {/* 视频标题 */}
                {title}
            </div>}
            <Loading
                visible={loading}
                tips="缓冲中"
                color='rgb(72, 188, 255)'
                type="4"
            >
            <div className="video">
                <canvas 
                    ref={canvas}
                    id = "canvas"
                    onMouseDown={playPause}
                    className={isMobile()?'noMobile':'mobile'}
                    style={{width:'100%'}}
                    width={canvasWh.width} 
                    height={canvasWh.height} 
                ></canvas>
                <video 
                    ref={video} 
                    src={src}
                    className={isMobile()?'mobile':'noMobile'}
                    style={{width:'100%'}}
                    onMouseDown={playPause}
                    // style={mobile && {width:'100%',height:'100%',left:'0px',top:'0px',zIndex:'auto'}}
                    controls = {false}
                    preload="metadata"
                >
                <source src={src} type="video/mp4"></source>
                <source src={src} type="video/ogg"></source>
                <source src={src} type="video/webm"></source>
                当前文件不是mp4、ogg文件
            </video>
            </div>
            </Loading>
            {innerControls && <> <div className={`controls animated faster ${animated?'fadeIn':'fadeOut'}`}>
                <Process
                    total={total}
                    current={current}
                    style={{
                        color:'white'
                    }}
                    onClick={(currentTime) =>{
                        // console.log(currentTime)
                        if(video.current.duration > 0){
                            video.current.currentTime = currentTime
                            setCurrent(currentTime)
                            video.current.play()
                        }
                    }}
                />
                <div className="btns">
                    <div className="leftBtns">
                        <i 
                            className='buttons iconfont icon-a-zhongboshuaxin'
                            onClick={_rePlay}  
                        ></i>
                        <i 
                            className={`buttons iconfont ${video.current?.paused?'icon-bofang':'icon-zanting'}`}
                            onClick={_playPause}
                        ></i>
                        <i 
                            className='buttons iconfont icon-24gf-next'
                            onClick={()=>{if(next)next()}}
                        ></i>
                    </div>

                    <div className="rightBtns">
                        <i 
                            className={`buttons iconfont audio ${video.current?.muted?'icon-shengyinjingyin':'icon-shengyin'}`}
                            onClick={_muted}
                        ></i>
                        <i className={`buttons audio`}>
                        <div className="setaudio">
                                <Process
                                    total={100}
                                    current={video.current?.volume * 100}
                                    showTime={false}
                                    disable = {video.current?.muted}
                                    onClick={(current) =>{
                                        // console.log(currentTime)
                                        if(!video.current.muted){
                                            video.current.volume = current/100
                                        }
                                    }}
                                />
                            </div>
                        </i>
                        <i 
                            className={`buttons iconfont ${full?'icon-guanbiquanping':'icon-quanping'}`}
                            onClick={_fullOrExit}
                        ></i>
                    </div>
                </div>
            </div> </>} 
            {/* {Video.current && <ContextMenu menus={[
                    {name:'播放',onclick:()=>{
                        video.current.play()
                    }},{name:'暂停',onclick:()=>{
                        video.current.pause()
                    }},{name:'静音',onclick:()=>{
                        video.current.muted = true
                    }}
                ]}
                target = {Video.current}
            />} */}
        </div>
    )
}
Video.propTypes = {
    src:string, 
    autoPlay:bool, 
    title:string, 
    next:func
}
Video.defaultProps = {
    src:'', 
    autoPlay:true, 
    title:'视频标题', 
    next:()=>{

    }
}
export default Video